<script setup lang='ts' name="personnel-organizational-add">
import type { FormInstance } from 'element-plus'

import { addOrganizationUser, addOrgUserForIam, departmentList, getAdminUserDetail, getBaseCityList, getRoleList } from '@fl/api/iam-api'
import FlUpload from '@fl/components/fl-upload.vue'
import { ElButton, ElCard, ElCol, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRadioGroup, ElRow, ElSelect } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { useTable as useTable2 } from '../../../hooks/use-table'
import { useRule } from '../../hooks/use-rule'

const { rules } = useRule()
// const router = useRouter()
const { go } = useRouter()
const route = useRoute()

const _userId = route.query?.userId as string
const userId = ref(_userId ?? '')

const _uuId = route.query?.uuId as string
const uuId = ref(_uuId ?? '')

const _deptId = route.query?.deptId as string
const deptId = ref(_deptId ?? '')

const _enterpriseObjectID = route.query?.enterpriseObjectID as string
const enterpriseObjectID = ref(_enterpriseObjectID ?? '')

const catTypeIdStr = route.query?.catTypeId as string
const catTypeIdArr = catTypeIdStr.split(',')
const hasIamBusiness = catTypeIdArr.some(tId => ['9', '10'].includes(tId)) // 9适老化、10电梯加装
// console.log('route.query', route.query)

const isLoading = ref(true)

const { arrayToTree } = useTable2()
const equityOptions = ref<any>([])
const equityOptionsOrigin = ref<any>([])
const roleOptions = ref<any>([])
const areaCascaderRef = ref<any>({})
const areaTreeData = ref<any[]>([])
const form = ref<any>({
    avatar: '',
    certificate: '',
    deptId: '',
    email: '',
    enterpriseAccount: '', // 登录名
    newRoleId: '',
    scope: [],
    parentId: '', // 父级部门
    phonenumber: '',
    status: '0',
    userName: '',
})

form.value.deptId = deptId.value

// 角色
function getRoleListData() {
    getRoleList().then((res) => {
        // console.log('role res', res)
        roleOptions.value = res.rows.reduce((pre, cur) => {
            cur.label = cur.roleName
            cur.value = String(cur.roleId)
            pre.push(cur)
            return pre
        }, [])
    })
}

// 组织机构树
function getTreeData() {
    departmentList({ enterprise: userId.value }).then((res) => {
        equityOptionsOrigin.value = cloneDeep(res.data)
        equityOptions.value = arrayToTree(res.data, 'parentId', 'deptId')
        // console.log('tree res', equityOptions.value)
    })
}

function getAreaDatas() {
    getBaseCityList().then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
            // 给每个节点添加 disabled 字段
            // const addDisabledField = (nodes) => {
            //     return nodes.map(node => {
            //         return {
            //             ...node,
            //             disabled: node.cityLevel === 1,
            //             children: node.children ? addDisabledField(node.children) : []
            //         };
            //     });
            // };
            // const cloneData = cloneDeep(data)
            // areaData.value = addDisabledField(cloneData)
            areaTreeData.value = data
        } else {
            ElMessage.error(msg)
        }
    })
}

const formRef = ref()

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            try {
                const { scope, ...rest } = form.value
                // const selectedNodes = areaCascaderRef.value.getCheckedNodes()
                // const shortAreaName = selectedNodes.map(node => node.label).join(',')
                const res1 = await addOrganizationUser({
                    isEdit: !!uuId.value,
                    params: {
                        ...rest,
                        enterpriseObjectID: enterpriseObjectID.value,
                        userId: Number(userId.value),
                        shortAreaCode: scope.join(','),
                        uuid: uuId.value,
                    },
                })
                let isSuccess = res1.code === 200

                if (hasIamBusiness) {
                    const res2 = await addOrgUserForIam({
                        isEdit: !!uuId.value,
                        params: {
                            scope: scope.join(','),
                            userName: `${userId.value}-${form.value.enterpriseAccount}`
                        },
                    })
                    isSuccess = isSuccess && res2.code === 200
                }

                if (isSuccess) {
                    ElMessage.success('保存成功')
                    close()
                } else {
                    ElMessage.error('保存失败')
                }
            } catch (err) {
                console.error(err)
            }
        }
        else {
            console.log('error submit!', fields)
        }
    })
}

function close() {
    go(-1)
}

async function init() {
    if (uuId.value) {
        getAdminUserDetail(uuId.value).then((res: any) => {
            if (res.code === 200) {
                form.value = {
                    avatar: res.data.avatar || '',
                    certificate: res.data.certificate || '',
                    deptId: res.data.deptId,
                    email: res.data.email,
                    enterpriseAccount: res.data.enterpriseAccount, // 登录名
                    newRoleId: res.data.newRoleId,
                    scope: res.data.shortAreaCode ? res.data.shortAreaCode.split(',') : [],
                    parentId: res.data.parentId, // 父级部门
                    phonenumber: res.data.phonenumber,
                    status: res.data.status,
                    userName: res.data.userName,
                }
                isLoading.value = false
                // console.log('init', form.value)
            }
        })
    }
    else {
        isLoading.value = false
    }
    getRoleListData()
    getTreeData()

    if (hasIamBusiness) {
        getAreaDatas()
    }
}
init()

// 选择部门
function deptIdChange(value) {
    // console.log('选中', value)
    const target = equityOptionsOrigin.value.find((v: any) => v.deptId === value[value.length - 1])
    // console.log('deptIdChange', target)
    form.value.deptId = target.deptId
}
</script>

<template>
    <ElCard>
        <div mb-40>
            <ElButton @click="close">
                返回列表
            </ElButton>
        </div>

        <el-skeleton v-if="isLoading"
                     animated
        />

        <ElForm v-else
                ref="formRef"
                :model="form"
                label-width="auto"
                :rules="rules"
                label-position="top"
        >
            <ElFormItem label="头像"
                        prop="avatar"
            >
                <FlUpload v-model="form.avatar" />
            </ElFormItem>

            <ElFormItem label="姓名"
                        prop="userName"
            >
                <ElInput v-model="form.userName" />
            </ElFormItem>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="手机号"
                                prop="phonenumber"
                    >
                        <ElInput v-model="form.phonenumber" maxlength="11" />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="邮箱"
                                prop="email"
                    >
                        <ElInput v-model="form.email" />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="登录名"
                                prop="enterpriseAccount"
                    >
                        <ElInput v-model="form.enterpriseAccount" maxlength="20" :disabled="!!uuId"/>
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElFormItem label="从业资格证书"
                        prop="certificate"
            >
                <FlUpload v-model="form.certificate" />
            </ElFormItem>

            <ElRow :gutter="20">
                <ElCol :span="8">
                    <ElFormItem label="所属部门"
                                prop="deptId"
                    >
                        <el-cascader v-model="form.deptId"
                                     :options="equityOptions"
                                     :props="{ label: 'deptName', value: 'deptId', checkStrictly: true }"
                                     :show-all-levels="false"
                                     class="w-full"
                                     @change="deptIdChange($event)"
                        />
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8">
                    <ElFormItem label="角色"
                                prop="newRoleId"
                    >
                        <ElSelect v-model="form.newRoleId"
                                  placeholder="请选择"
                        >
                            <ElOption v-for="item in roleOptions"
                                      :key="item.value"
                                      :label="item.label"
                                      :value="item.value"
                            />
                        </ElSelect>
                    </ElFormItem>
                </ElCol>

                <ElCol :span="8" v-if="hasIamBusiness">
                    <ElFormItem label="行政区域短码">
                        <el-cascader ref="areaCascaderRef"
                                     v-model="form.scope"
                                     :options="areaTreeData"
                                     :props="{
                                         multiple: true,
                                         checkStrictly: true,
                                         emitPath: false,
                                         value: 'extAreaCode',
                                         label: 'areaName',
                                        //  children: 'areaList',
                                     }"
                                     :show-all-levels="false"
                                     clearable
                                     class="w-full"
                        />
                    </ElFormItem>
                </ElCol>
            </ElRow>

            <ElFormItem label="账号状态"
                        prop="status"
            >
                <ElRadioGroup v-model="form.status">
                    <ElRadio value="0">
                        正常
                    </ElRadio>

                    <ElRadio value="1">
                        停用
                    </ElRadio>
                </ElRadioGroup>
            </ElFormItem>

            <ElFormItem flex
                        flex-col
            >
                <div text-center
                     style="width:100%"
                >
                    <ElButton type="primary"
                              @click="doSave(formRef)"
                    >
                        确定
                    </ElButton>

                    <ElButton @click="close">
                        取消
                    </ElButton>
                </div>
            </ElFormItem>
        </ElForm>
    </ElCard>
</template>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
    position: relative;
    overflow: hidden;
    cursor: pointer;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    width: 178px;
    height: 178px;
    font-size: 28px;
    color: #8c939d;
    text-align: center;
}
</style>
